﻿using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Threading.Tasks;
using LabNet.Server.Configuration;
using LabNet.Server.Domain;

namespace LabNet.Server.Data
{
    public class DefaultContext : DbContext, IDataContext
    {
        public DefaultContext():base("Default")
        {
            
        }

        public DefaultContext(string nameOrConnectionString)
            :base(nameOrConnectionString)
        {
            
        }
        public virtual IDbSet<User> Users { get; set; }
        public virtual IDbSet<UserLogin> UserLogins { get; set; }
        public virtual IDbSet<UserClaim> UserClaims { get; set; }
        public virtual IDbSet<UserRole> UserRoles { get; set; }
        public virtual IDbSet<Role> Roles { get; set; }
        public virtual IDbSet<Group> Groups { get; set; }
        public virtual IDbSet<UserGroup> UserGroups { get; set; }
        public virtual IDbSet<RoleGroup> RoleGroups { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
            UserConfiguration.Map(modelBuilder);
            UserLoginConfiguration.Map(modelBuilder);
            UserClaimConfiguration.Map(modelBuilder);
            UserRoleConfiguration.Map(modelBuilder);
            RoleConfiguration.Map(modelBuilder);
            UserGroupConfiguration.Map(modelBuilder);
            RoleGroupConfiguration.Map(modelBuilder);
        }


        public virtual int Commit()
        {
            return base.SaveChanges();
        }

        public virtual async Task<int> CommitAsync()
        {
            return await base.SaveChangesAsync();
        }

        public virtual IDbSet<T> DbSet<T>() where T : BaseObject
        {
            return Set<T>();
        }

        public new DbEntityEntry Entry<T>(T entity) where T : BaseObject
        {
            return base.Entry(entity);
        }
    }
}
